//index.js
//获取应用实例
var app = getApp();
//console.log(app.globalData);
Page({
  data: {
    userInfo: {},
    region: [],
    customItem: '全部',
    status:0,  
    location:'',
    address:'',
    id:0,
    store_id:0,
    community_name:'',
  },
  chooseLocation:function(){
    var that = this;
    wx.chooseLocation({
      success:function(res){
        console.log(res);
        that.setData({ location: res});
       
      },
      fail:function(res){
        app.alert(res.msg);
      }
    });
  },
  reset:function(){
    this.setData ( {
      userInfo: {},
      location:'',
      address:'',
      community_name:'',
      disabled:0,
      loading:0,
      hotline:'',
      id:0,
    });
  },
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
  },
  onShow:function(){
   
    var id = app.getPageData("index/issue", "id");
    if (id) {
      this.data.id = id;
      this.init();
      app.setPageData("index/issue", { id: 0 });
    }
  },
  init:function(){
    var that = this;
    app.api("community/find", {
      id: this.data.id,
    }, function (res) {
      that.data.loading = 0;
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      var poi = res.data.community_locations.split("|")
      that.setData({
        community_name: res.data.community_name,
        store_id: res.data.store_id,
        hotline: res.data.hotline,
        location:{
          address: res.data.community_address,
          longitude: poi[0],
          latitude: poi[1]
        }
      });
    })
  },
  
  formSubmit:function(e){
    var postData = e.detail.value;
    if (postData.title==""){
      app.alert("请输入小区名称");
      return false;
    }
    if (postData.hotline == "") {
      app.alert("请输入管理员手机号");
      return false;
    }
    if (this.data.location == "") {
      app.alert("请选择地理位置");
      return false;
    }
    var that = this;
    that.setData({ 'loading': 1 });
    that.setData({ 'disabled': 1 });
    app.api("community/add",{
      method: 'POST',
      store_id: this.data.store_id,
      id: this.data.id,
      hotline: postData.hotline,
      community_name: postData.community_name,
      community_address: this.data.location.address,
      community_locations: this.data.location.longitude + "|" + this.data.location.latitude
    },function(res){
      if (res.code != 200) {
        app.alert(res.msg);
        that.data.payloading = 0;
        that.setData({ 'loading': 0 });
        that.setData({ 'disabled': 0 });
        return false;
      }
      that.reset();
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      })
      app.setPageData("user/community", { reload: 1 });
      wx.navigateTo({
        url: '/pages/user/community_detail?id'+res.data.id,
      })
    })
    
  }
  
  
})
